//
//  XLMakeVoiceChatVC.m
//  XiangLove
//
//  Created by 李传坤 on 2018/8/8.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLMakeVoiceChatVC.h"
#import "MZTimerLabel.h"
#import "UIImage+WebP.h"
//#import "LiveUIRightView.h"
#import "KeyboardView.h"
#import "GiftModel.h"
#import "YFGIFImageView.h"
//#import "GifAniOpertaionManager.h"
//#import "ChatOperationManage.h"
#import "TXCVideoPreprocessor.h"
#import "BeautySettingPanel.h"
#import "TopUpViewController.h"
#import "XLUserInfoModel.h"
#import "XLAccountManager.h"
#import "XLHTTPSessionManager.h"
#import <ReactiveCocoa.h>
#import "XLUserSideEstimateVC.h"
#import "XLTalkThemeSheetView.h"
#import <Lottie/Lottie.h>
@interface XLMakeVoiceChatVC ()<TILCallNotificationListener,TILCallStatusListener, TILCallMemberEventListener,AVAudioPlayerDelegate,KeyboardViewDelegate,TXIVideoPreprocessorDelegate,QAVLocalVideoDelegate,BeautySettingPanelDelegate,MZTimerLabelDelegate>
{
    AVAudioPlayer * _audioPlayer;
    
}
@property (nonatomic, strong) TILC2CCall         *call;
@property (nonatomic, strong) UIImageView        *backimage;
@property (nonatomic, strong) UIImageView        *headImae;
@property (nonatomic, strong) UILabel            *nameLabel;
@property (nonatomic, strong) UILabel         *inforLabel;//xinxi
@property (nonatomic, strong) UILabel            *gradeLabel;
@property (nonatomic, strong) UILabel            *detailLabel;
@property (nonatomic, strong) UILabel            *moneyLab;
@property (nonatomic, strong) UIButton           *closeBtn;
@property (nonatomic, strong) UILabel            *closeLab;
@property (nonatomic, assign) BOOL                thmeAnimalfinish;//判断问题动画是否完成;
@property (nonatomic, assign) BOOL                giftAnimalfinish;//判断礼物动画是否完成;
@property (nonatomic, strong) UIButton           *cinemaBtn;
@property (nonatomic, strong) UILabel            *meiyanLab;
@property (nonatomic, strong) UIButton           *micButton;
@property (nonatomic, strong) UILabel            *micLab;
@property (nonatomic, strong) UIButton        *miantiButton;//免提button
@property (nonatomic, strong) UILabel         *miantiLab;//免提label
@property (nonatomic, assign) BOOL                isring;
@property (nonatomic, strong) MZTimerLabel       *timer;
@property (nonatomic, strong) NSTimer            *everyTimer;
@property (nonatomic, strong) NSTimer            *aduioPlayTimer;
@property (nonatomic, strong) NSTimer            *heartBeatTimer;
@property (nonatomic, strong) NSTimer            *heartChcek;         //心跳OBJC
@property (nonatomic, assign) BOOL                isBaseDid;
@property (nonatomic, strong) AVAudioSession     *audioSession;
@property (nonatomic, strong) NSString           *myId;
//@property (nonatomic, strong) LiveUIRightView    *RightView;

@property (nonatomic, strong) UIButton           *giftBtn;
@property (nonatomic, strong) UIButton           *giftBtnSmall;

@property (nonatomic, strong) UILabel            *giftLab;
@property (nonatomic, strong) UIButton           *chatThemeBtn;

@property (nonatomic, strong) KeyboardView       *keyboardView;
@property (nonatomic, strong) XLTalkThemeSheetView       *TalkThemeSheetView;
@property (nonatomic, strong) NSMutableArray     *senderGiftArr;
@property (nonatomic, strong) YFGIFImageView     *gifview;
@property (nonatomic, strong) UIImageView        *gifImageView;
@property (nonatomic, strong) UIWindow           *thewindow;
@property (nonatomic, assign) BOOL                isFirst;
@property (nonatomic, assign) BOOL                isRemand;
@property (nonatomic, assign) BOOL                isReceived;
@property (nonatomic, assign) BOOL                isEnderMoney;

@property (nonatomic, strong) BeautySettingPanel *vBeauty;
@property (nonatomic, strong) TXCVideoPreprocessor *preProcessor;
@property (nonatomic, assign) Byte  *processorBytes;

@property (nonatomic, assign) TXEBeautyStyle beautyType;
@property (nonatomic, assign) NSInteger BeautyLevel;
@property (nonatomic, assign) NSInteger WhitenessLevel;
@property (nonatomic, assign) NSInteger RuddinessLevel;
@property (nonatomic, assign) TXEFilterType FilterType;
@property (nonatomic, strong) UIImage *FilterUIImage;
@property (nonatomic, assign) CGFloat FilterMixLevel;
@property (nonatomic, copy  ) NSString *GreenScreenFile;
@property (nonatomic, assign) NSInteger EyeScaleLevel;
@property (nonatomic, assign) NSInteger FaceSlimLevel;
@property (nonatomic, assign) NSInteger FaceBeautyLevel;
@property (nonatomic, assign) NSInteger FaceVLevel;
@property (nonatomic, assign) NSInteger ChinLevel;
@property (nonatomic, assign) NSInteger FaceShortLevel;
@property (nonatomic, assign) NSInteger NoseSlimLevel;
@property (nonatomic, copy  ) NSString *MotionTemplate;
@property (nonatomic, strong) UIView   *bottomView;
@property (nonatomic, strong) NSTimer  *moneyStatTimer;
@property (nonatomic, strong) XLUserInfoModel *userInfoModel;
@property (nonatomic, strong) LOTAnimationView *launchAnimation;

@end

@implementation XLMakeVoiceChatVC

#pragma mark -
- (void)praiseAnimation {
    UIImageView *imageView = [[UIImageView alloc] init];
    CGRect frame = self.view.frame;
    //  初始frame，即设置了动画的起点
    imageView.frame = CGRectMake(50, frame.size.height - 65, 60, 60);
    //  初始化imageView透明度为0
    imageView.alpha = 0;
    imageView.backgroundColor = [UIColor clearColor];
    imageView.clipsToBounds = YES;
    //  用0.2秒的时间将imageView的透明度变成1.0，同时将其放大1.3倍，再缩放至1.1倍，这里参数根据需求设置
    [UIView animateWithDuration:0.2 animations:^{
        imageView.alpha = 1.0;
        imageView.frame = CGRectMake(frame.size.width - 40, frame.size.height - 90, 30, 30);
        CGAffineTransform transfrom = CGAffineTransformMakeScale(1.3, 1.3);
        imageView.transform = CGAffineTransformScale(transfrom, 1, 1);
    }];
    [self.view addSubview:imageView];
    //  随机产生一个动画结束点的X值
    CGFloat finishX = frame.size.width - 50;
    //  动画结束点的Y值
    CGFloat finishY = 100;
    //  imageView在运动过程中的缩放比例
    CGFloat scale = round(random() % 2) + 0.7;
    // 生成一个作为速度参数的随机数
    CGFloat speed = 1 / round(random() % 900) + 0.6;
    //  动画执行时间
    NSTimeInterval duration = 4 * speed;
    //  如果得到的时间是无穷大，就重新附一个值（这里要特别注意，请看下面的特别提醒）
    if (duration == INFINITY) duration = 2.412346;
    // 随机生成一个0~7的数，以便下面拼接图片名
    int imageName = round(random() % 8);
    
    //  开始动画
    [UIView beginAnimations:nil context:(__bridge void *_Nullable)(imageView)];
    //  设置动画时间
    [UIView setAnimationDuration:duration];
    
    //  拼接图片名字
    //    imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"good%d_30x30_.png",imageName]];
    imageView.image = [UIImage imageNamed:@"home_but_jieting_n"];
    //  设置imageView的结束frame
    imageView.frame = CGRectMake( finishX, finishY, 30 * scale, 30 * scale);
    
    //  设置渐渐消失的效果，这里的时间最好和动画时间一致
    [UIView animateWithDuration:duration animations:^{
        imageView.alpha = 0;
    }];
    
    //  结束动画，调用onAnimationComplete:finished:context:函数
    [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
    //  设置动画代理
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}
/// 动画完后销毁iamgeView
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    UIImageView *imageView = (__bridge UIImageView *)(context);
    [imageView removeFromSuperview];
    imageView = nil;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.isEnderMoney = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_TalkThemeSheetView removeFromSuperview];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [HelpTool statStartEventId:@"109" eventLabel:@"1对1视频聊界面"];
}
#pragma mark *************获取礼物列表
-(void)getFlowerList
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"5", @"type",nil];
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/Gift/GetGiftList" parameters:dic resultClass:nil] subscribeNext:^(id x) {
        [self getSenderGiftArr:x];
    } error:^(NSError *error) {
        
    }];
    
}

- (void)getSenderGiftArr:(NSMutableArray *)arr {
    for (int i = 0; i < arr.count; i++) {
        GiftModel *giftModer = [[GiftModel alloc] initWithDict:arr[i]];
        [self.senderGiftArr addObject:giftModer];
    }
    [self.view reloadInputViews];
}


- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reaciveGiftMessage:)name:@"videoGiftMessage" object:nil];//礼物发送
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reacveQuestion:)name:@"ChatThemeAndQuestion" object:nil];//话题指令
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hangupWithNoManny) name:@"hangupYuebuzu" object:nil];//余额不足服务器指令强制挂段
    [[NSNotificationCenter defaultCenter] postNotificationName:@"makecall" object:nil];
    self.userInfoModel = [[XLAccountManager shareInstance] model];
    self.preProcessor = [[TXCVideoPreprocessor alloc] init];
    [self.preProcessor setDelegate:self];
    
    _thewindow = kDeviceWindow;
    self.view.backgroundColor = [UIColor blackColor];
    self.isBaseDid = NO;_thmeAnimalfinish = YES;_giftAnimalfinish = YES;
    //    self.isFirst = YES;
    self.isRemand = YES;
    [self makecallwaitPlay];
    [self makeCall];
    [self initMakeUI];
    NSLog(@"bbbbbbbbbbbb === %@", [[ILiveLoginManager getInstance] getLoginId]);
    [self setEnableButton:NO];
    self.senderGiftArr = [NSMutableArray array];
    [self getFlowerList];
    _myId = [[ILiveLoginManager getInstance] getLoginId];
    [[ILiveRoomManager getInstance] setLocalVideoDelegate:self];
    
    IMAMsg *msg = [IMAMsg chatMsgWithText:@"请求语音聊天"];
    IMAUser *user;
    user.userId = _peerId;
    
    _conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:_peerId];
    [_conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
        
    }];
    
    _receiverKVO = [FBKVOController controllerWithObserver:self];
    _conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:self.peerId];
    __weak XLMakeVoiceChatVC *ws = self;
    _conversation.receiveMsg = ^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
        
        TIMElem *meaage = [msg.msg getElem:0];
        if ([meaage isKindOfClass:[TIMCustomElem class]]){
            TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
            CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
            if (elemCmd.msgType == 3) {
                if ([elemCmd.giftBubbleImage rangeOfString:@"gif"].location != NSNotFound ) {
//                    [ws addGifPicWithIndexXX:elemCmd.giftBubbleImage withName:elemCmd.giftName];
                    
                }else {
//                    [ws addGifImageView:elemCmd.giftMsgImage withName:elemCmd.giftName];
                    
                }
                
            }else {
                
            }
        }
    };
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.isEnderMoney == YES) {
        if (self.iscall == 1) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"chatrefreshMessage" object:nil];
            
        }
        [self.everyTimer invalidate];
        self.everyTimer = nil;
        [self.heartChcek invalidate];
        self.heartChcek = nil;
        [self.moneyStatTimer invalidate];
        self.moneyStatTimer = nil;
        
        [_audioPlayer stop];
        //        self.isFirst = NO;
        self.call = nil;
        [self.heartBeatTimer invalidate];
        self.heartBeatTimer = nil;
        self.isRemand = NO;
        [UserDefaults removeObjectForKey:ChatToChatCallId];
        
        [UserDefaults removeObjectForKey:kVideoID];
        [UserDefaults synchronize];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallup) object:nil];
        //        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallupAPI) object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    }
    
}

-(void)makecallwaitPlay
{
    
    NSString *audioFile=[[NSBundle mainBundle] pathForResource:@"微信语音提示音" ofType:@"mp3"];
    NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
    NSError *error;
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    _audioPlayer.delegate = self;
    _audioPlayer.volume =1.0;
    
    
    [_audioPlayer prepareToPlay];
    
    
    
    if (_audioPlayer == nil) {
        
        NSLog(@"播放音频%@", [error description]);
        
    }
    
    else{
        
        [self palyOne];
        
    }
    
    
}


-(void)palyOne
{
    self.audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [self.audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
    _audioPlayer.numberOfLoops = 1;
    if (!_audioPlayer.isPlaying) [_audioPlayer play];
    else _audioPlayer.currentTime = 0.0f;
    
}

- (void)stop
{
    [_audioPlayer stop];
    
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
    //播放结束时执行的动作
    NSLog(@"===播放结束了====");
    [self palyOne];
    
    
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{
    //解码错误执行的动作
    NSLog(@"===解码错误了====");
}

#pragma mark -
#pragma mark - ***************MakeUI
/**
 初始化
 */
- (void)initMakeUI {
    
    UIImageView *backimage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, XQScreenH)];
    backimage.image = [UIImage imageNamed:@"video_bg_yaoqing_n.png"];
    backimage.backgroundColor = [UIColor clearColor];
    backimage.userInteractionEnabled = YES;
    self.backimage = backimage;
    _launchAnimation = [LOTAnimationView animationNamed:@"soundWave"];
    _launchAnimation.cacheEnable = NO;
    _launchAnimation.frame = CGRectMake(ScreenWidth/2-130, ScreenHeight/2 - 200, 260, 260);
    _launchAnimation.contentMode = UIViewContentModeScaleToFill;
    _launchAnimation.animationSpeed = 1;_launchAnimation.loopAnimation = YES;
    [_launchAnimation play];
    [backimage addSubview:_launchAnimation];
    UIImageView *headImae = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth/2 - 60,ScreenHeight/2 - 130, 120, 120)];
    headImae.backgroundColor = [UIColor whiteColor];
    headImae.layer.cornerRadius = 60;
    headImae.layer.masksToBounds = YES;
    [headImae sd_setImageWithURL:[NSURL URLWithString:self.headStr] placeholderImage:[UIImage imageNamed:@"BeautyPlaceholder"]];
    [backimage addSubview:headImae];
    self.headImae = headImae;
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.font = [UIFont systemFontOfSize:21];
    nameLabel.numberOfLines = 1;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.text = self.nickNameStr;
    [backimage addSubview:nameLabel];
    nameLabel.frame = CGRectMake(20 ,50, [UIScreen mainScreen].bounds.size.width, 40);
    self.nameLabel = nameLabel;
    UILabel *inforLabel = [[UILabel alloc] init];
    inforLabel.textAlignment = NSTextAlignmentCenter;
    inforLabel.font = [UIFont systemFontOfSize:15];
    inforLabel.textColor = [UIColor whiteColor];
    [backimage addSubview:inforLabel];
    inforLabel.hidden = YES;
    self.inforLabel = inforLabel;
    
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.frame = CGRectMake(20, 90, [UIScreen mainScreen].bounds.size.width, 20);
    detailLabel.textAlignment = NSTextAlignmentLeft;
    detailLabel.font = [UIFont systemFontOfSize:14];
    detailLabel.numberOfLines = 1;
    detailLabel.textColor = [UIColor whiteColor];
    detailLabel.text =@"正在等待对方接听...";
    self.detailLabel = detailLabel;
    [backimage addSubview:detailLabel];
    [self.view addSubview:backimage];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 100, [UIScreen mainScreen].bounds.size.width, 100)];
    bottomView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomView];
    UIView *middleView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 200, [UIScreen mainScreen].bounds.size.width, 100)];
    middleView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:middleView];
    //礼物
    UIButton *giftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    giftBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50, 30, 40, 40);
    [giftBtn setImage:[UIImage imageNamed:@"video_icon_liwu_n"] forState:UIControlStateNormal];
    giftBtn.hidden = YES;
    self.giftBtn = giftBtn;
    [giftBtn addTarget:self action:@selector(handleGiftBtn:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:giftBtn];
    //小礼物
    UIButton *giftBtnSmall = [UIButton buttonWithType:UIButtonTypeCustom];
    giftBtnSmall.frame = CGRectMake(15, 10, 60, 60);
    [giftBtnSmall setImage:[UIImage imageNamed:@"momoda_icon"] forState:UIControlStateNormal];
    giftBtnSmall.hidden = YES;
    self.giftBtnSmall = giftBtnSmall;
    [giftBtnSmall addTarget:self action:@selector(handleSmallGiftBtn:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:giftBtnSmall];
    //话题
    UIButton *chatThemeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    chatThemeBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 100, 30, 40, 40);
    [chatThemeBtn setImage:[UIImage imageNamed:@"video_icon_huati_n"] forState:UIControlStateNormal];
    chatThemeBtn.hidden = NO;
    self.chatThemeBtn = chatThemeBtn;
    [chatThemeBtn addTarget:self action:@selector(showChatChemeView:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:chatThemeBtn];
    
    self.bottomView = bottomView;
    
    
    //取消拨打
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/ 2 - 35, SCREEN_HEIGHT - 120, 70, 70);
    [closeBtn setImage:[UIImage imageNamed:@"call_icon_guaduan_default"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(handleCloseBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.closeBtn = closeBtn;
    UILabel *closeLab = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/ 2 - 45, SCREEN_HEIGHT - 50, 90, 20)];
    closeLab.text = @"取消";
    closeLab.textAlignment = NSTextAlignmentCenter;
    closeLab.font = [UIFont systemFontOfSize:13];
    closeLab.textColor = [UIColor whiteColor];
    self.closeLab = closeLab;
    
    [self.view addSubview:closeLab];
    [self.view addSubview:closeBtn];
    //免提
    UIButton *miantiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    miantiButton.frame = CGRectMake(ScreenWidth/ 3 - 35 , 0, 70, 70);
    [miantiButton setImage:[UIImage imageNamed:@"video_icon_handfree_n"] forState:UIControlStateNormal];
    miantiButton.layer.masksToBounds = YES;
    miantiButton.layer.cornerRadius = 35;
    miantiButton.hidden = YES;
    [miantiButton addTarget:self action:@selector(handleSpeakerButton:) forControlEvents:UIControlEventTouchUpInside];
    self.miantiButton = miantiButton;
    [middleView addSubview:miantiButton];
    //免提
    UILabel *miantiLab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/3 - 35, 70, 70, 20)];
    miantiLab.text = @"免提";
    miantiLab.textAlignment = NSTextAlignmentCenter;
    miantiLab.font = [UIFont systemFontOfSize:13];
    miantiLab.textColor = [UIColor whiteColor];
    miantiLab.hidden = YES;
    self.miantiLab = miantiLab;
    [middleView addSubview:miantiLab];
    //麦克风
    UIButton *micButton = [UIButton buttonWithType:UIButtonTypeCustom];
    micButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/ 3 *2 - 35 , 0, 70, 70);
    [micButton setImage:[UIImage imageNamed:@"video_icon_quite_n"] forState:UIControlStateNormal];
    micButton.layer.masksToBounds = YES;
    micButton.layer.cornerRadius = 35;
    micButton.hidden = YES;
    [micButton addTarget:self action:@selector(handleMicButton:) forControlEvents:UIControlEventTouchUpInside];
    self.micButton = micButton;
    [middleView addSubview:micButton];
    //麦克风
    UILabel *micLab = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/ 3 *2 - 35, 70, 70, 20)];
    micLab.text = @"静音";
    micLab.textAlignment = NSTextAlignmentCenter;
    micLab.font = [UIFont systemFontOfSize:13];
    micLab.textColor = [UIColor whiteColor];
    micLab.hidden = YES;
    self.micLab = micLab;
    [middleView addSubview:micLab];
    [self getUserInfor];
}
#pragma mark 切换麦克风
- (void)handleMicButton:(UIButton *)sender {
    
    ILiveRoomManager *manager = [ILiveRoomManager getInstance];
    BOOL isOn = [manager getCurMicState];
    if (isOn == YES) {
        _micLab.text = @"已静音";
        [_micButton setImage:[UIImage imageNamed:@"video_icon_quite_s"] forState:UIControlStateNormal];
        
    }else{
        _micLab.text = @"静音";
        [_micButton setImage:[UIImage imageNamed:@"video_icon_quite_n"] forState:UIControlStateNormal];
        
    }
    [manager enableMic:!isOn succ:^{
        
    } failed:^(NSString *moudle, int errId, NSString *errMsg) {
        
    }];
    
}
#pragma mark 扬声器
- (void)handleSpeakerButton:(UIButton *)sender {
    
    ILiveRoomManager *manager = [ILiveRoomManager getInstance];
    BOOL isOn = [manager getCurSpeakerState];
    if (isOn == YES) {
        _miantiLab.text = @"听筒";
        [_miantiButton setImage:[UIImage imageNamed:@"video_icon_handfree_s"] forState:UIControlStateNormal];
        
    }else{
        _miantiLab.text = @"免提";
        [_miantiButton setImage:[UIImage imageNamed:@"video_icon_handfree_n"] forState:UIControlStateNormal];
        
    }
    [manager enableSpeaker:!isOn succ:^{
        
    } failed:^(NSString *moudle, int errId, NSString *errMsg) {
        
    }];
    
}
- (void)getUserInfor{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/VideoChat/GetVoiceUserInfo" parameters:@{@"userId":_peerId} resultClass:nil] subscribeNext:^(id x) {
        NSDictionary *dic = x;
        if (![dic[@"HostCity"] isKindOfClass:[NSNull class]]) {
            NSString *sex = [dic[@"Sex"] integerValue] == 1 ? @"男":@"女";
            _inforLabel.text = [NSString stringWithFormat:@"%@  %@",dic[@"HostCity"],sex];
        }
    } error:^(NSError *error) {
        
    }];
}
#pragma mark - 发起方取消／挂断
/**
 
 发叫方取消／挂断
 @param sender IsRing(NO取消 YES挂断)
 
 */
- (void)handleCloseBtn:(UIButton *)sender {
    sender.userInteractionEnabled = NO;
    __weak typeof(self) ws = self;
    if (self.isring == NO) {
        [self addBtnDidType:@"9" andAtype:@"1"];
        [self callMakeEndCall:@"2"];
        [self messageOfsenderComment:1];//用户取消
        [self.call cancelCall:^(TILCallError *err) {
            [ws stop];
            ws.call = nil;
            [ws dismissViewControllerAnimated:YES completion:nil];
        }];
        
    }else {//
        [self callMakeEndCall:@"7"];
        [self messageOfsenderComment:3];//用户挂断
        [self selfDismiss];
    }
}
- (void)reacveQuestion:(NSNotification *)infor{
    NSDictionary *dic = infor.userInfo;
    [self amimalChatQuestion:dic[@"chatQuestion"]];
}
#pragma mark - **********展开话题
- (void)showChatChemeView:(UIButton *)sender {
    [_TalkThemeSheetView removeFromSuperview];
    _TalkThemeSheetView = [[XLTalkThemeSheetView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    @weakify(self);
    _TalkThemeSheetView.block = ^(NSString *themeId) {
        @strongify(self);
        [self getQuestionWithThemeId:themeId];
    };
    [_TalkThemeSheetView getChatThemeListReloadData1:_callid];
    [_TalkThemeSheetView show];
    
}
#pragma mark - **********获取聊天的问题
- (void)getQuestionWithThemeId:(NSString *)themeId{
    NSDictionary *dic = @{@"callId":_callid,@"typeId":themeId,@"sendId":self.userInfoModel.Id,@"receiveId":_peerId};
    if (_thmeAnimalfinish == YES) {
        [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/VideoChat/GetTopic" parameters:dic resultClass:nil]subscribeNext:^(id x) {
            //发送问题
            if (![x isKindOfClass:[NSNull class]]) {
                IMAMsg *msgs = [IMAMsg msgWithCustom:9 chatQuestion:x[@"Content"]];
                [self giftMessageOfsenderComment:msgs];
                [self amimalChatQuestion:x[@"Content"]];
            }
        } error:^(NSError *error) {
            
        }];
    }else{
        [MBProgressHUD showContent:@"操作太快了哦!" toView:self.view];
    }
}
- (void)amimalChatQuestion: (NSString *)QUESTION{
    _thmeAnimalfinish = NO;
    UILabel *ChatQuestonLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, ScreenHeight/2-50, ScreenWidth-60, 100)];
    ChatQuestonLabel.textAlignment = NSTextAlignmentCenter;
    ChatQuestonLabel.textColor = [UIColor whiteColor];
    ChatQuestonLabel.text = QUESTION;
    ChatQuestonLabel.font = [UIFont systemFontOfSize:25 weight:UIFontWeightHeavy];
    ChatQuestonLabel.numberOfLines = 2;
    [self.view addSubview:ChatQuestonLabel];
    ChatQuestonLabel.transform = CGAffineTransformMakeScale(0.5, 0.5);
    [self.TalkThemeSheetView removeFromSuperview];
    // 弹簧动画，参数分别为：时长，延时，弹性（越小弹性越大），初始速度
    [UIView animateWithDuration: 0.9 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:0.2 options:0 animations:^{
        // 放大
        ChatQuestonLabel.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                _thmeAnimalfinish = YES;
                [ChatQuestonLabel removeFromSuperview];
            });
        });
        //        [self performSelector:@selector(hidenChatQuestionAnimal) withObject:nil afterDelay:5];
    }];
}
- (void)hidenChatQuestionAnimal{
    
}
#pragma mark -  **********送小礼物
- (void)handleSmallGiftBtn:(UIButton *)sender {
    if(_senderGiftArr.count>0){
        GiftModel *model = _senderGiftArr[0];
        [self keyboardViewDidSendUrl:@"" moverImageUrl:@"" name:@"" price:0.2 giftID:model.Id];
    }
    
}
#pragma mark -  **********充值跳转
-(void)keyboardViewChargeBtn{
    self.isEnderMoney = NO;
    TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
    topVC.In_purchase = NO;
    topVC.backActionBlock = ^() {
        [self dismissViewControllerAnimated:YES completion:NULL];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:topVC];
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark -  **********礼物展示
- (void)handleGiftBtn:(UIButton *)sender {
    [_TalkThemeSheetView removeFromSuperview];
    self.keyboardView = [[KeyboardView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height) array:self.senderGiftArr WithColor:RGBA_HEX(0x0C0D10, 0.95) withIslive:NO];
    self.keyboardView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.3];
    
    self.keyboardView.mydelegate = self;
    
    [self.view addSubview:self.keyboardView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [self.keyboardView addGestureRecognizer:tapGesture];
    
}

#pragma mark -  **********送礼物
- (void)keyboardViewDidSendUrl:(NSString *)imageUrl moverImageUrl:(NSString *)moverUrl name:(NSString *)name price:(float)price giftID:(NSInteger)giftID {
    if (_giftAnimalfinish == YES) {
        _giftAnimalfinish = NO;
        
        NSLog(@"vvvvvvvv == %@ --- %@", imageUrl, [[NSUserDefaults standardUserDefaults] objectForKey:UserID]);
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[NSString stringWithFormat:@"%ld", (long)giftID],@"giftId",[[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"giveUserId",self.peerId, @"giftsUserId", [NSString stringWithFormat:@"%f", price], @"giftPrice", @"1", @"giftNumber",@"",@"Intro",_callid,@"DynamicID", nil];
        [[[XLHTTPSessionManager sharedManager]XLV2POST:@"/Api/v2/Gift/GiveGift" parameters:dicRegister resultClass:nil] subscribeNext:^(id x) {
            NSLog(@"礼物僧送==-=-=-=-=-=-%@", x);
            
            if (x != nil) {
                //            IMAMsg *msgs = [IMAMsg msgWithCustom:3 priceStr:[NSString stringWithFormat:@"%0.f", price * 10] giftBubbleImageUrl:moverUrl giftMsgImageUrl:imageUrl NameStr:name];
                //            [self giftMessageOfsenderComment:msgs];
                if (giftID != 109) {
                    [MBProgressHUD showContent:@"赠送成功" toView:self.view];
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
                
            }else if (x) {
                [self.keyboardView removeFromSuperview];
                
                [HelpTool startTipViewWithText:@"余额不足" duration:1 type:kTipViewTypeNone];
                
                
            }else {
                self.isEnderMoney = NO;
                TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                topVC.In_purchase = NO;
                topVC.backActionBlock = ^() {
                    [self dismissViewControllerAnimated:YES completion:NULL];
                };
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:topVC];
                
                [self presentViewController:nav animated:YES completion:nil];
            }
        } error:^(NSError *error) {
            _giftAnimalfinish = YES;
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
        }];
    }else{
        
    }
    
}

- (void)hide
{
    
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        
        
    } completion:^(BOOL finished)
     {
         [self.keyboardView removeFromSuperview];
     }];
}

- (void)dealloc {
    NSLog(@"dealloc %@", [self class]);
}

#pragma mark -

#pragma mark - 发起方扣钱API

/**
 发起方-扣费接口(每分钟调一次)
 */
//callSuccessMinuteCost
-(void)callSuccessMinuteCostWithType:(NSString *)costType
{
    
    __weak typeof(self) ws = self;
    
    NSString *uid = [NSString stringWithFormat:@"%@",NSUser_object(UserID)];
    NSString *callVideoID = self.videoid;
    NSString *peeridStr = self.peerId;
    
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    NSDictionary * videoDic = [NSDictionary dictionaryWithObjectsAndKeys:costType,@"Type",uid,@"Userid",peeridStr,@"Anchorid", @"2",@"Rtype",[NSString stringWithFormat:@"%@",callVideoID],@"Id",locationString,@"Timestamp",natUser,@"Appsign",nil];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:videoDic success:^(id  _Nullable JSON) {
        //        NSLog(@"ffffffddddd == %@", JSON);
        if ([costType isEqualToString:@"7"]) {
            NSString  *status  =  JSON[@"result"][@"data"][@"Status"];
            NSString  *minute  =  JSON[@"result"][@"data"][@"Minute"];
            if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"3"])
            {
                //扣费成功！
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
                
            }else if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"-1"])
            {
                [HelpTool startTipViewWithText:@"您的用户余额不足，请充值!" duration:2.0f type:kTipViewTypeNone];
                [self callMakeEndCall:@"9"];
                [ws messageOfsenderComment:3];//用户挂断
                
                [self selfDismiss];
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
                
                
            }else if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"-2"])
            {
                [HelpTool startTipViewWithText:@"通话已结束!" duration:2.0f type:kTipViewTypeNone];
                [ws messageOfsenderComment:3];//用户挂断
                [self selfDismiss];
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
                
            }else if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"-10"])
            {
                [HelpTool startTipViewWithText:@"扣费失败!" duration:2.0f type:kTipViewTypeNone];
                [ws messageOfsenderComment:3];//用户挂断
                [self selfDismiss];
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
                
            }
            if ([minute intValue] <= 10) {
                if (self.isRemand == YES) {
                    self.isRemand = NO;
                    //                    [HelpTool startTipViewWithText:[NSString stringWithFormat:@"您可以聊天%d分钟",[minute intValue]] duration:2.0f type:kTipViewTypeNone];
                }
            }
            
        }
        NSLog(@"===通话扣费接口====%@",JSON);
    } failure:^(NSError * _Nullable error) {
        NSLog(@"===通话扣费接口失败===%@",error);
        
    }];
}


#pragma mark -扣费接口(NEW)
-(void)callSuccessMinuteCostNew
{
//    NSString *uid         = [NSString stringWithFormat:@"%@",NSUser_object(UserID)];
//    NSString *callVideoID = self.videoid;
//    NSString *peeridStr   = self.peerId;
//    @weakify(self);
//    [[[XLHTTPSessionManager sharedManager] getVideoChatDiscountD:callVideoID callUserID:uid Anchorid:peeridStr] subscribeNext:^(id x) {
//        @strongify(self);
//        NSString  *status  = [NSString stringWithFormat:@"%@",x[@"Result"]];
//        NSString  *minute  = [NSString stringWithFormat:@"%@",x[@"Minute"]];
//        if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"3"])
//        {
//            //扣费成功！
//            [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
//
//        }else if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"-1"])
//        {
//            [HelpTool startTipViewWithText:@"您的用户余额不足，请充值!" duration:2.0f type:kTipViewTypeNone];
//            [self callMakeEndCall:@"9"];
//            [self messageOfsenderComment:3];//用户挂断
//
//            [self selfDismiss];
//            [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
//
//
//        }else if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"-2"])
//        {
//            [HelpTool startTipViewWithText:@"通话已结束!" duration:2.0f type:kTipViewTypeNone];
//            [self messageOfsenderComment:3];//用户挂断
//            [self selfDismiss];
//            [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
//
//        }else if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"-10"])
//        {
//            [HelpTool startTipViewWithText:@"扣费失败!" duration:2.0f type:kTipViewTypeNone];
//            [self messageOfsenderComment:3];//用户挂断
//            [self selfDismiss];
//            [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
//
//        }
//        if ([minute intValue] <= 10) {
//            if (self.isRemand == YES) {
//                self.isRemand = NO;
//                //                [HelpTool startTipViewWithText:[NSString stringWithFormat:@"您可以聊天%d分钟",[minute intValue]] duration:2.0f type:kTipViewTypeNone];
//            }
//        }
//
//    } error:^(NSError *error) {
//        NSLog(@"扣费失败;;;;;%@",error);
//
//    }];
    
    
}


#pragma mark -

#pragma mark - 挂断API
/**
 挂断API
 */
-(void)callhangupEnd
{
    //    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    //    NSString *callVideoID = self.videoid;
    //    NSString *peeridStr = self.peerId;
    //
    //    NSDate * senddate=[NSDate date];
    //    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    //    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    //    NSString *locationString = [dateformatter stringFromDate:senddate];
    //    //令牌
    //    NSDate *now = [NSDate date];
    //    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    //    fmt.dateFormat = kBMHRequestTimeFormat;
    //
    //    NSString *sTimeUser = [fmt stringFromDate:now];
    //    NSString *objIDUser = @"0";
    //    NSString *publicKeyUser = @"BMH2014YDYWB";
    //    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
    //    natUser = [natUser md5Encrypt];
    //
    //
    //    NSDictionary * videoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"Type",uid,@"Userid",peeridStr,@"Anchorid", @"2",@"Rtype",[NSString stringWithFormat:@"%@",callVideoID],@"Id",locationString,@"Timestamp",natUser,@"Appsign",nil];
    //    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:videoDic success:^(id  _Nullable JSON) {
    //        NSString * errcode  = JSON[@"result"][@"errcode"];
    //
    //        if ([errcode isEqualToString:@"0"])
    //        {
    //
    //            //[HelpTool startTipViewWithText:@"通话结束成功!" duration:2.0f type:kTipViewTypeNone];
    //
    //
    //        }else{
    //
    //            //[HelpTool startTipViewWithText:@"通话结束失败!" duration:2.0f type:kTipViewTypeNone];
    //        }
    //
    //
    //        NSLog(@"===通话结束接口====%@",JSON);
    //    } failure:^(NSError * _Nullable error) {
    //        NSLog(@"===通话结束接口失败===%@",error);
    //
    //    }];
    
    
}

#pragma mark -

//#pragma mark - 心跳API
///**
// 心跳API 每20s发送一次心跳
// */
//-(void)everyHeartBeat:(id)sender
//{
//
//    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
//    NSString *callVideoID = self.videoid;
//    NSString *peeridStr = self.peerId;
//    NSString *HeartBeatcallID = self.callid;
//
//    NSDate * senddate=[NSDate date];
//    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
//    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
//    NSString *locationString = [dateformatter stringFromDate:senddate];
//    //令牌
//    NSDate *now = [NSDate date];
//    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//    fmt.dateFormat = kBMHRequestTimeFormat;
//
//    NSString *sTimeUser = [fmt stringFromDate:now];
//    NSString *objIDUser = @"0";
//    NSString *publicKeyUser = @"BMH2014YDYWB";
//    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
//    natUser = [natUser md5Encrypt];
//
//
//    NSDictionary * videoDic = [NSDictionary dictionaryWithObjectsAndKeys:
//                                                                         @"11",@"type",
//                                                               HeartBeatcallID,@"callId",
//                                                                           uid,@"userId",
//                                                                     peeridStr,@"anchorId",
//                                                                          @"1",@"iFlag",
//                                                                       natUser,@"Appsign",
//
//                                                                         nil];
//
//    [BMHHTTPSession GET:@"MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:videoDic success:^(id  _Nullable JSON) {
//
//        BMHLog(@"===心跳API==%@",JSON);
//        NSString  *status  =  JSON[@"result"][@"data"];
//        if ([[NSString stringWithFormat:@"%@",status] isEqualToString:@"0"]) {
//
//            [self heartbeatCallupAPI];
//        }
//
//
//    } failure:^(NSError * _Nullable error) {
//
//    }];
//
//
//
//}

#pragma mark -
#pragma mark - 心跳停止

/**
 心跳停止 -挂断API
 */
-(void)heartbeatCallup
{
    
    [HelpTool startTipViewWithText:@"对方网络已断" duration:2.0f type:kTipViewTypeNone];
    
    [self callMakeEndCall:@"13"];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallup) object:nil];
    [self selfDismiss];
}

//-(void)heartbeatCallupAPI
//{
//    [HelpTool startTipViewWithText:@"对方网络已断" duration:2.0f type:kTipViewTypeNone];
//
//    [self addBtnDidType:@"10" andAtype:@"14"];
//    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallupAPI) object:nil];
//    [self selfDismiss];
//}


#pragma mark - 发起方通话配置

- (void)makeCall{
    TILCallManager *manager = [TILCallManager sharedInstance];
    NSString *version = [manager getVersion];
    NSLog(@"%@", version);
    
    TILCallConfig * config = [[TILCallConfig alloc] init];
    TILCallBaseConfig * baseConfig = [[TILCallBaseConfig alloc] init];
    baseConfig.callType = TILCALL_TYPE_AUDIO;
    baseConfig.isSponsor = YES;
    baseConfig.peerId = _peerId;
    baseConfig.heartBeatInterval = 5;
    baseConfig.autoHdAudio = YES;
    baseConfig.autoCamera = NO;
    baseConfig.autoMic = YES;
    baseConfig.autoSpeaker = YES;
    baseConfig.isAutoResponseBusy = YES;
    config.baseConfig = baseConfig;
    
    TILCallListener * listener = [[TILCallListener alloc] init];
    //注意：
    //［通知回调］可以获取通话的事件通知，建议双人和多人都走notifListener
    // [通话状态回调] 也可以获取通话的事件通知
    listener.callStatusListener = self;
    listener.memberEventListener = self;
    listener.notifListener = self;
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    config.callListener = listener;
    TILCallSponsorConfig *sponsorConfig = [[TILCallSponsorConfig alloc] init];
    sponsorConfig.waitLimit = 30;
    sponsorConfig.callId = [_callid intValue];
    sponsorConfig.onlineInvite = NO;
    sponsorConfig.controlRole = @"userA";
    config.sponsorConfig = sponsorConfig;
    
    
    self.call = [[TILC2CCall alloc] initWithConfig:config];
    
//    [self.call createRenderViewIn:self.view];
    
    UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 140, 40, 120, 160)];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleBaseTap:)];
    [baseView addGestureRecognizer:tap];
    [self.view addSubview:baseView];
    __weak typeof(self) ws = self;
    
    self.userInfoModel = [[XLAccountManager shareInstance] model];
    NSString * myName  = [NSString stringWithFormat:@"%@",self.userInfoModel.NickName];
    NSString * myHead  = [NSString stringWithFormat:@"%@",self.userInfoModel.HeadImg];
    NSString * myGrade = [NSString stringWithFormat:@"1"];
    NSString * myCity  = [NSString stringWithFormat:@"%@",self.userInfoModel.HostCity];
    NSString * myAge   = [NSString stringWithFormat:@"%ld",(long)self.userInfoModel.Age];
    NSString * myJob   = [NSString stringWithFormat:@"1"];
    NSString * callid   = self.callid;
    
    //ChatToChatCallId
    
    //携带自定义消息(userInfo)
    NSDictionary * myInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:myName,@"name",myHead,@"headimg",myGrade,@"leval",myCity,@"address",myAge,@"age",myJob,@"job", @([callid intValue]),@"newRecordId",self.isAuto ? @(1) : @(0), @"isMatchCall", nil];
    // newRecordId
    NSString * jsonStr = [self dictionaryToJson:myInfoDic];
    
    [self.call makeCall:jsonStr custom:jsonStr result:^(TILCallError *err) {
        NSLog(@"eeeeeerrr === %@  -- %@ -- %d", err.errMsg, err.domain, err.code);
        if(err){
            
            [ws dismissViewControllerAnimated:YES completion:nil];
        }
        else{
            
            ILiveRoomManager *manager = [ILiveRoomManager getInstance];
            if (ws.iscinema == NO) {
                
                
                
                [manager enableCamera:CameraPosFront enable:NO succ:^{
                    
                } failed:^(NSString *module, int errId, NSString *errMsg) {
                    
                }];
                [manager enableCamera:CameraPosBack enable:NO succ:^{
                    
                } failed:^(NSString *module, int errId, NSString *errMsg) {
                    
                }];
                
                
            }else {
              
                [manager enableCamera:CameraPosFront enable:YES succ:^{
                    
                } failed:^(NSString *module, int errId, NSString *errMsg) {
                    
                }];
                
            }
            
            if (ws.ismic == NO) {
                
                
                [manager enableMic:NO succ:^{
                    
                    
//                    BOOL isOns = [manager getCurMicState];
//                    ws.micLab.text = isOns ?@"关闭麦克风":@"打开麦克风";
//                    [ws.micButton setImage:[UIImage imageNamed:isOns ?@"videoMicClose":@"videoMicOpen"] forState:UIControlStateNormal];
                    
                    
                    
                } failed:^(NSString *module, int errId, NSString *errMsg) {
                    
                }];
            }else{
                
                
                [manager enableMic:YES succ:^{
                    
//                    BOOL isOns = [manager getCurMicState];
//                    ws.micLab.text = isOns ?@"关闭麦克风":@"打开麦克风";
//                    [ws.micButton setImage:[UIImage imageNamed:isOns ?@"videoMicClose":@"videoMicOpen"] forState:UIControlStateNormal];
                    
                } failed:^(NSString *module, int errId, NSString *errMsg) {
                    
                }];
                
            }
            
            [manager setBeauty:5.0];
            [manager setWhite:5.0];
            
//            NSString *myId = [[ILiveLoginManager getInstance] getLoginId];
//            [ws.call addRenderFor:myId atFrame:CGRectMake(SCREEN_WIDTH -135, 50, 120, 160)];
        }
    }];
    
}


-(NSString*)dictionaryToJson:(NSDictionary *)dict

{
    
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}




/**
 交换渲染位置
 
 @param sender 大小画面
 */
- (void)handleBaseTap:(UITapGestureRecognizer *)sender {
    
    [_call switchRenderView:_peerId with:_myId];
    
}

#pragma mark - 计时器代理
-(void)timerLabel:(MZTimerLabel*)timerLabel countingTo:(NSTimeInterval)time timertype:(MZTimerLabelType)timerType{
    NSString *second = [NSString stringWithFormat:@"%f",time];
    NSString *second2 = [[second componentsSeparatedByString:@"."]firstObject];
    NSInteger integer = [second2 integerValue] % (15);
    if ([second2 integerValue] > 0 && integer == 0) {
        [self koufei];
    }
    NSLog(@"33333333333333%f",time);
    NSLog(@"44444444444444%@",timerLabel.text);
}

#pragma mark - 扣费
- (void)koufei{
    NSDictionary *dic = @{@"type":@"1",
                          @"userId":[[XLAccountManager shareInstance]model].Id,
                          @"anchorId":_peerId,
                          @"callId":_callid
                          };
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/VideoChat/Connect1v1Charge" parameters:dic resultClass:nil] subscribeNext:^(id x) {
        NSLog(@"%@",x);

    } error:^(NSError *error) {
        if (error.code == 6) {
            [self callMakeEndCall:@"9"];
            [self selfDismiss];
        }
    }];
}
#pragma mark - 消息事件(建立通话成功）

/**
 消息事件(建立通话成功
 
 */
- (void)onCallEstablishwithSuccess{
    [self stop];
    [self.audioSession setCategory :AVAudioSessionCategoryRecord error:nil];
    self.moneyStatTimer =  [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(startToGiveMoney) userInfo:nil repeats:NO];
    [self callSuccessMinuteCostWithType:@"17"];
    self.timer = [[MZTimerLabel alloc] initWithLabel:self.closeLab andTimerType:MZTimerLabelTypeStopWatch];
    self.timer.delegate = self;
    [self.timer start];
    
    AVAudioSession * session = [AVAudioSession sharedInstance];
    NSError *sessionError = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    AudioSessionSetProperty (
                             kAudioSessionProperty_OverrideAudioRoute,
                             sizeof (audioRouteOverride),
                             &audioRouteOverride
                             );
#pragma clang diagnostic pop
    if(!session) {
        DebugLog(@"Error creating session: %@", [sessionError description]);
    }
    else {
        [session setActive:YES error:nil];
    }
    
    ILiveRoomManager *manager = [ILiveRoomManager getInstance];
    BOOL isOn = [manager getCurMicState];
    [manager setAudioMode:QAVOUTPUTMODE_SPEAKER];
    _closeLab.frame = CGRectMake(SCREEN_WIDTH - 80 , 30, 60, 20);
    _closeBtn.frame = CGRectMake(10, 30, 40, 40);
    [_closeBtn setImage:[UIImage imageNamed:@"video_icon_chacha_n1"] forState:UIControlStateNormal];
    [_launchAnimation stop];
    [_launchAnimation removeFromSuperview];
    self.micButton.hidden = NO;
    self.micLab.hidden = NO;
    self.miantiButton.hidden = NO;
    self.miantiLab.hidden = NO;
    self.inforLabel.hidden = NO;
    self.detailLabel.hidden = YES;
    self.nameLabel.frame = CGRectMake(0, _headImae.frame.origin.y + 135, ScreenWidth, 20);
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.inforLabel.frame = CGRectMake(0, _headImae.frame.origin.y + 160, ScreenWidth, 20);
    [self setEnableButton:YES];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        self.moneyLab.hidden = YES;
    });
}



- (void)startToGiveMoney {
    
    self.everyTimer =  [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(everyTimeMinuteCost:) userInfo:nil repeats:YES];
    [self callSuccessMinuteCostNew];
}

-(void)everyTimeMinuteCost:(id)sender
{
    [self callSuccessMinuteCostNew];
}

#pragma mark - 成员有视频流事件
/**
 成员有视频流事件
 
 @param isOn    YES 开启视频流
 @param members TILCallMember*列表
 */

- (void)onMemberCameraVideoOn:(BOOL)isOn members:(NSArray *)members{
//    if(isOn){
//        for (TILCallMember *member in members) {
//            NSString *identifier = member.identifier;
//            if([identifier isEqualToString:_myId]){
//                [_call addRenderFor:_myId atFrame:CGRectMake(SCREEN_WIDTH - 140, 50, 120, 160)];
//            }
//            else{
//                [_call addRenderFor:identifier atFrame:self.view.bounds];
//                [_call sendRenderViewToBack:identifier];
//
//            }
//        }
//    }
//    else{
//        for (TILCallMember *member in members) {
//            NSString *identifier = member.identifier;
//            [_call removeRenderFor:identifier];
//        }
//    }
}
- (void)onMemberAudioOn:(BOOL)isOn members:(NSArray*)members{
    
}

#pragma mark - 事件通知类型

/**
 事件通知类型
 */
- (void)onRecvNotification:(TILCallNotification *)notify
{
    
    NSInteger notifId = notify.notifId;
    switch (notifId) {
        case TILCALL_NOTIF_ACCEPTED:
            //            if (self.isFirst == YES) {
            //                self.isFirst = NO;
            self.isReceived = YES;
            [self onCallEstablishwithSuccess];
            [self performSelector:@selector(heartbeatCallup) withObject:nil afterDelay:20];
            
            //            }
            break;
        case TILCALL_NOTIF_TIMEOUT: {
            [HelpTool startTipViewWithText:@"对方没有接听" duration:2.0f type:kTipViewTypeNone];
            [self addBtnDidType:@"9" andAtype:@"3"];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:self.peerId];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
            }];
            [self messageOfsenderComment:1];//超时取消
            [_audioPlayer stop];
            [self callMakeEndCall:@"4"];//超时
            [self selfDismiss];
        }
            break;
        case TILCALL_NOTIF_REFUSE: {
            [HelpTool startTipViewWithText:@"对方已拒绝" duration:2.0f type:kTipViewTypeNone];
            [self selfDismiss];
        }
            break;
        case TILCALL_NOTIF_HANGUP: {
            [HelpTool startTipViewWithText:@"对方已挂断" duration:2.0f type:kTipViewTypeNone];
            [self selfDismiss];
        }
            break;
        case TILCALL_NOTIF_LINEBUSY: {
            [HelpTool startTipViewWithText:@"对方正忙" duration:2.0f type:kTipViewTypeNone];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:self.peerId];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
            }];
            [self selfDismiss];
        }
            break;
        case TILCALL_NOTIF_HEARTBEAT: {
            if (self.isReceived) {
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartbeatCallup) object:nil];
                [self performSelector:@selector(heartbeatCallup) withObject:nil afterDelay:20];
            }
        }
            break;
        case TILCALL_NOTIF_DISCONNECT: {
            [HelpTool startTipViewWithText:@"失去连接" duration:2.0f type:kTipViewTypeNone];
            [self selfDismiss];
        }
            break;
        default:
            break;
    }
}

#pragma mark -





- (void)messageOfsenderComment:(int)commentTag {
    
    NSDictionary *myInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@(commentTag), @"command",self.peerId,@"callId",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"rejectId",nil];
    NSString * jsonStr = [self dictionaryToJson:myInfoDic];
    NSLog(@"gangjinru == %@", myInfoDic);
    NSDictionary *groupDic = [NSDictionary dictionaryWithObjectsAndKeys:@(12),@"action",jsonStr,@"videoPhoneMessage", nil];
    TIMMessage *msg = [[TIMMessage alloc] init];
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    elem.data = [NSJSONSerialization dataWithJSONObject:groupDic options:NSJSONWritingPrettyPrinted error:nil];
    [msg addElem:elem];
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:_peerId];
    [con sendMessage:msg succ:^{
    } fail:^(int code, NSString *msg) {
        
    }];
    
}

- (void)giftMessageOfsenderComment:(IMAMsg *)msg {
    [_conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
        
    }];
    TIMElem *meaage = [msg.msg getElem:0];
    if ([meaage isKindOfClass:[TIMCustomElem class]]) {
        TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
        CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
        if (elemCmd.msgType == 3) {
            if ([elemCmd.giftBubbleImage rangeOfString:@"gif"].location != NSNotFound ) {
//                [self addGifPicWithIndexXX:elemCmd.giftBubbleImage withName:elemCmd.giftName];
                
            }else {
//                [self addGifImageView:elemCmd.giftMsgImage withName:elemCmd.giftName];
                
            }
            
        }else {
            
        }
    }
}

//- (void)addGifImageView:(NSString *)gifStr  withName:(NSString *)namestr{
//    MagMeaageModel *magMessageModel = [[MagMeaageModel alloc] init];
//    magMessageModel.giftCount = 1;
//    magMessageModel.senderId = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
//    magMessageModel.giftImageUrl = gifStr;
//    magMessageModel.giftName = namestr;
//    ChatOperationManage *gifmanager = [ChatOperationManage sharedManager];
//    gifmanager.parentView = self.view;
//    // 用用户唯一标识 msg.senderChatID 存礼物信息,model 传入礼物模型
//    [gifmanager animWithUserID: magMessageModel.giftMoveImageUrl model:magMessageModel finishedBlock:^(BOOL result) {
//
//    }];
//}
//#pragma mark **********礼物动画
//- (void)addGifPicWithIndexXX:(NSString *)gifStr withName:(NSString *)namestr{
//    MagMeaageModel *magMessageModel = [[MagMeaageModel alloc] init];
//    magMessageModel.giftCount = 1;
//    magMessageModel.senderId = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
//    magMessageModel.giftMoveImageUrl = gifStr;
//    magMessageModel.giftName = namestr;
//    GifAniOpertaionManager *gifmanager = [GifAniOpertaionManager sharedManager];
//    gifmanager.parentView = self.view;
//    // 用用户唯一标识 msg.senderChatID 存礼物信息,model 传入礼物模型
//    [gifmanager animWithUserID: magMessageModel.giftMoveImageUrl model:magMessageModel finishedBlock:^(BOOL result) {
//
//    }];
//
//}
- (void)hangupWithNoManny{
    [self callMakeEndCall:@"14"];
    [self selfDismiss];
//    [HelpTool startTipViewWithText:@"余额不足请充值" duration:2.0f type:kTipViewTypeNone];
}
- (void)selfDismiss
{
    self.isEnderMoney = YES;
    [_vBeauty saveValues];
    __weak typeof(self) ws = self;
    
    [self.call hangup:^(TILCallError *err) {
        [ws stop];
        [ws.everyTimer invalidate];
        ws.everyTimer = nil;
        [ws.timer pause];
        [ws.heartBeatTimer invalidate];
        ws.heartBeatTimer = nil;
        [ws.heartChcek invalidate];
        ws.heartChcek = nil;
        [ws.moneyStatTimer invalidate];
        ws.moneyStatTimer = nil;
        ws.call = nil;
        
        //        [ws dismissViewControllerAnimated:YES completion:nil];
        
    }];
    [ws dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)setEnableButton:(BOOL)isMake{
    self.isring = isMake;
    
    self.giftBtn.hidden = !isMake;
//    self.giftBtnSmall.hidden = !isMake;
    self.chatThemeBtn.hidden = !isMake;
    self.giftLab.hidden = !isMake;
}

#pragma mark - aType 7，正常挂断；9，余额不足挂断；12，callsdk内部心跳异常挂断；14，秀趣心跳接口异常挂断
- (void)addBtnDidType:(NSString *)type andAtype:(NSString *)atype {
    //type=9&userId=&anchorId=&callId=&aType=
    
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSString *callVideoID = [[NSUserDefaults standardUserDefaults] objectForKey:kVideoID];
    NSString *peeridStr = self.peerId;
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:type, @"type",atype, @"aType",self.peerId,@"anchorId",NSUser_object(UserID),@"userId",self.callid,@"callId",natUser,@"appsign",nil];
    
    [BMHHTTPSession GET:@"MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:dic success:^(id  _Nullable JSON) {
        NSLog(@"flowwwwwddddddd == %@",JSON);
    } failure:^(NSError * _Nullable error) {
        
    }];
}

-(void)callMakeEndCall:(NSString *)endType
{
    
    [[[XLHTTPSessionManager sharedManager] getVideoChatEndCallID:self.callid userId:NSUser_object(UserID) anchorId:self.peerId endType:endType] subscribeNext:^(id x) {
        NSLog(@"挂断啦！！！");
    } error:^(NSError *error) {
        
    }];
}



#pragma mark - 相机权限检测

- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

#pragma mark - BeautySettingPanelDelegate
- (void)onSetBeautyStyle:(int)beautyStyle beautyLevel:(float)beautyLevel whitenessLevel:(float)whitenessLevel ruddinessLevel:(float)ruddinessLevel {
    self.beautyType = beautyStyle;
    self.BeautyLevel = beautyLevel;
    self.WhitenessLevel = whitenessLevel;
    self.RuddinessLevel = ruddinessLevel;
}

- (void)onSetEyeScaleLevel:(float)eyeScaleLevel
{
    self.EyeScaleLevel = eyeScaleLevel;
}

- (void)onSetFaceScaleLevel:(float)faceScaleLevel
{
    self.FaceSlimLevel = faceScaleLevel;
}

- (void)onSetFilter:(UIImage*)filterImage
{
    self.FilterUIImage = filterImage;
}

- (void)onSetGreenScreenFile:(NSURL *)file
{
    self.GreenScreenFile = [file absoluteString];
}

- (void)onSelectMotionTmpl:(NSString *)tmplName inDir:(NSString *)tmplDir
{
    self.MotionTemplate = [tmplDir stringByAppendingPathComponent:tmplName];
}

- (void)onSetFaceVLevel:(float)faceVLevel{
    self.FaceVLevel = faceVLevel;
}

- (void)onSetChinLevel:(float)chinLevel{
    self.ChinLevel = chinLevel;
}

- (void)onSetNoseSlimLevel:(float)slimLevel{
    self.NoseSlimLevel = slimLevel;
}

- (void)onSetFaceShortLevel:(float)faceShortlevel{
    self.FaceShortLevel = faceShortlevel;
}

- (void)onSetMixLevel:(float)mixLevel{
    self.FilterMixLevel = mixLevel / 10.0;
}

#pragma mark - QAVLocalVideoDelegate
- (void)OnLocalVideoPreProcess:(QAVVideoFrame *)frameData
{
    [self.preProcessor setBeautyStyle:self.beautyType];
    [self.preProcessor setBeautyLevel:self.BeautyLevel];
    [self.preProcessor setWhitenessLevel:self.WhitenessLevel];
    [self.preProcessor setRuddinessLevel:self.RuddinessLevel];
    [self.preProcessor setFilterType:self.FilterType];
    [self.preProcessor setFilterUIImage:self.FilterUIImage];
    [self.preProcessor setFilterMixLevel:self.FilterMixLevel];
    [self.preProcessor setGreenScreenFile:self.GreenScreenFile];
    //    [self.preProcessor setEyeScaleLevel:self.EyeScaleLevel];
    //    [self.preProcessor setFaceSlimLevel:self.FaceSlimLevel];
    [self.preProcessor setFaceBeautyLevel:self.FaceBeautyLevel];
    //    [self.preProcessor setFaceVLevel:self.FaceVLevel];
    //    [self.preProcessor setChinLevel:self.ChinLevel];
    //    [self.preProcessor setFaceShortLevel:self.FaceShortLevel];
    //    [self.preProcessor setNoseSlimLevel:self.NoseSlimLevel];
    //    [self.preProcessor setMotionTemplate:self.MotionTemplate];
    
    [self.preProcessor setOutputSize:CGSizeMake(frameData.frameDesc.width, frameData.frameDesc.height)];
    //开始预处理
    [self.preProcessor processFrame:frameData.data width:frameData.frameDesc.width height:frameData.frameDesc.height orientation:TXE_ROTATION_90 inputFormat:TXE_FRAME_FORMAT_NV12 outputFormat:TXE_FRAME_FORMAT_NV12];
    //将处理完的数据拷贝到原来的地址空间，如果是同步处理，此时会先执行（4）
    if(self.processorBytes){
        memcpy(frameData.data, self.processorBytes, frameData.frameDesc.width * frameData.frameDesc.height * 3 / 2);
    }
}

#pragma mark - TXIVideoPreprocessorDelegate
- (void)didProcessFrame:(Byte *)bytes width:(NSInteger)width height:(NSInteger)height format:(TXEFrameFormat)format timeStamp:(UInt64)timeStamp
{
    self.processorBytes = bytes;
}

- (void)onDetectFacePoints:(NSArray *)points {
    
}

#pragma mark --
#pragma mark - 屏幕方向改变
- (BOOL)shouldAutorotate
{
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return  UIInterfaceOrientationPortrait;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (void)reaciveGiftMessage:(NSNotification *)infor{
    IMAMsg *msg = infor.object;
    TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    NSDictionary *giftdic = [NSJSONSerialization JSONObjectWithData:elem.data options:0 error:nil];
    NSString *urlStringMove = elemCmd.giftBubbleImage;
    NSString *urlStringImg = elemCmd.giftMsgImage;
    NSString *idGift = [NSString stringWithFormat:@"%@",giftdic[@"giftId"]];
    CGFloat durition = 0.0;
    if ([idGift integerValue] == 110 || [idGift integerValue] == 111 || [idGift integerValue] == 112) {
        durition =  4.6;
    }else{
        durition = 8.5;
    }
    if (![idGift isEqualToString:@"109"]){//不是么么哒动画
        if (![urlStringMove isKindOfClass:[NSNull class]] && urlStringMove.length > 0) {//moveimage有数据
            if ([urlStringMove rangeOfString:@"webp"].location != NSNotFound){
                //读取
                NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *fileName = [[urlStringMove componentsSeparatedByString:@"/"]lastObject];
                NSString *imageFilePath = [path stringByAppendingPathComponent:fileName];
                NSError * error;
                NSData * data = [NSData dataWithContentsOfFile:imageFilePath options:NSDataReadingMappedIfSafe error:&error];
                if (data) {
                    UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                    [self.view addSubview:imageV];
                    UIImage * image = [UIImage sd_imageWithWebPData:data];
                    imageV.image = image;
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(durition * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [imageV removeFromSuperview];
                            _giftAnimalfinish = YES;
                        });
                    });
                }else{
                    NSLog(@"惨啦，没有拿到数据,去下载");
                    [self downloadWebp:urlStringMove time:durition];
                }
            }else{//webp不为空的普通动画
                _giftAnimalfinish = YES;
//                [self addGifImageView:urlStringImg withName:elemCmd.giftName];
            }
        }else{//webp为空的普通动画
            
        }
    }else{//是么么哒动画
        [self showMoreLoveAnimateFromView:nil addToView:self.view fromMe:YES];
    }
    
}
- (void)showMoreLoveAnimateFromView:(UIView *)fromView addToView:(UIView *)addToView fromMe:(BOOL)fromMe {
    _giftAnimalfinish = YES;
    CGFloat w = self.view.frame.size.width;
    CGFloat h = self.view.frame.size.height;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    
    //起点
    CGPoint position = CGPointMake(60, ScreenHeight - 60);
    
    imageView.layer.position = position;
    imageView.image = [UIImage imageNamed:@"momoda_icon"];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [addToView addSubview:imageView];
    
    //动画总时长
    CGFloat duration = 6;
    
    //形变动画1 变大
    [UIView animateWithDuration:duration/2 animations:^{
        imageView.transform = CGAffineTransformMakeScale(2, 2);
    }];
    
    //形变动画2 还原
    [UIView animateWithDuration:duration/2 delay:duration/2 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseIn animations:^{
        imageView.transform = CGAffineTransformIdentity;
    } completion:nil];
    
    //路径动画
    CAKeyframeAnimation *positionAnimate = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    positionAnimate.repeatCount = 1;
    positionAnimate.duration = duration;
    positionAnimate.fillMode = kCAFillModeForwards;
    positionAnimate.removedOnCompletion = NO;
    
    
    UIBezierPath *sPath = [UIBezierPath bezierPath];
    //设置三次贝塞尔曲线的起点
    [sPath moveToPoint:position];
    
    //第一个控制点
    int r1 = w - 40;//x的取值范围：[20, w - 20]
    int r2 = h - 40;//y的取值范围：[20, h - 20]
    CGPoint controlOne = CGPointMake((arc4random() % r1) + 20, (arc4random() % r2) + 20);
    UIView *p1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 5)];
    p1.backgroundColor = [UIColor blueColor];
    p1.center = controlOne;
    //    [self.view addSubview:p1];
    
    //第二个控制点
    int l1 = w - 40;
    int l2 = h - 40;
    CGPoint controlTwo = CGPointMake((arc4random() % l1) + 20, (arc4random() % l2) + 20);
    UIView *p2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 5)];
    p2.backgroundColor = [UIColor redColor];
    p2.center = controlTwo;
    //    [self.view addSubview:p2];
    
    //三次贝塞尔曲线的终点 （ w ，50）
    CGPoint endPoint = CGPointMake(w, 50);
    [sPath addCurveToPoint:endPoint controlPoint1:controlOne controlPoint2:controlTwo];
    positionAnimate.path = sPath.CGPath;
    
    [imageView.layer addAnimation:positionAnimate forKey:@"heartAnimated"];
    
    CAShapeLayer *l = [CAShapeLayer new];
    l.path  = sPath.CGPath;
    l.fillColor   = [UIColor clearColor].CGColor;
    l.strokeColor = [UIColor blackColor].CGColor;
    //    [self.view.layer addSublayer:l];
    
    [UIView animateWithDuration:duration animations:^{
        imageView.layer.opacity = 0;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        [l removeFromSuperlayer];
        [p1 removeFromSuperview];
        [p2 removeFromSuperview];
    }];
}
- (void)downloadWebp:(NSString *)urlString time:(CGFloat)durition{
    dispatch_queue_t queue2 = dispatch_queue_create("queue", NULL);
    dispatch_async(queue2, ^{
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [self.view addSubview:imageV];
        NSError * error;
        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString] options:NSDataReadingMappedIfSafe error:&error];
        if (data) {
            UIImage * image = [UIImage sd_imageWithWebPData:data];
            imageV.image = image;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(durition * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [imageV removeFromSuperview];
                    _giftAnimalfinish = YES;
                });
            });
        }else{
            NSLog(@"惨啦，没有拿到数据");
        }
    });
}

@end
